﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;

namespace DC.Views
{
    public partial class Form_OrderList : Skin_DevExpress
    {
        public Form_OrderList()
        {
            InitializeComponent();
        }

        Utils.Database DB = Utils.Global.GlobalDB;

        private void Form_OrderList_Load(object sender, EventArgs e)
        {
            LoadTable();
            LoadOrders();
        }

        private void LoadOrders()
        {
            OrderList.Rows.Clear();
            OrderList.Columns.Clear();
            LoadTable();

            string sql = "select * from Book where CONVERT(CHAR(10), Order_Time, 23) like '%" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "%'";
            DataView dv = DB.GetDs(sql).Tables[0].DefaultView; // 读取这一天的预约列表

            for (int i = 0; i < dv.Count; i++)
            {
                DataRow current = dv[i].Row;
                for (int j = 0; j < OrderList.ColumnCount; j++)
                {
                    if (current["User_ID"].ToString() == OrderList.Columns[j].Name) // 匹配值
                    {
                        DateTime dateTime = Convert.ToDateTime(current["Order_Time"]);
                        int hour = dateTime.Hour;
                        int lineid = hour - 8;
                        string name = DB.GetData("select Patient_Name from Patient where Patient_ID=" + current["Patient_ID"]).ToString();

                        OrderList.Rows[lineid].Cells[j].Tag = current["Order_ID"]; // 绑定OrderID到这个单元格
                        OrderList.Rows[lineid].Cells[j].Value = name + "\n" + current["Order_Things"].ToString();
                    }
                }
            }
        }

        /// <summary>
        /// 载入医生列表
        /// </summary>
        private void LoadTable()
        {
            // 先加一个时间格子
            OrderList.Columns.Add("Time", "时间");

            string sql = "select User_ID,Real_Name from [User]";
            DataView userlist = DB.GetDs(sql).Tables[0].DefaultView;
            for (int i = 0; i < userlist.Count; i++)
            {
                OrderList.Columns.Add(userlist[i]["User_ID"].ToString(), userlist[i]["Real_Name"].ToString());
            }

            for (int i = 0; i < 9; i++)
            {
                OrderList.Rows.Add();
                OrderList.Rows[i].Cells[0].Value = (i + 8).ToString() + ":00";
            }
        }

        private void OrderList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 || e.RowIndex == 0)
            {
                return;
            }
            Form_OrderInfo form_OrderInfo = new Form_OrderInfo();

            // 新增时传入值
            if (OrderList.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag == null) // 没有ID时则为新建
            {
                form_OrderInfo.type = "new";
                form_OrderInfo.Time = OrderList.Rows[e.RowIndex].Cells[0].Value.ToString();
                form_OrderInfo.DoctorID = OrderList.Columns[e.ColumnIndex].Name;
                form_OrderInfo.date = dateTimePicker1.Value.ToString("yyyy-MM-dd");
            }
            else
            {
                // 修改时传入ID
                form_OrderInfo.type = "modify";
                form_OrderInfo.Time = OrderList.Rows[e.RowIndex].Cells[0].Value.ToString();
                form_OrderInfo.DoctorID = OrderList.Columns[e.ColumnIndex].Name;
                form_OrderInfo.OrderID = OrderList.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag.ToString();
            }
            form_OrderInfo.ShowDialog();
            LoadOrders();
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            LoadOrders();
        }

        private void skinButton1_Click(object sender, EventArgs e)
        {
            dateTimePicker1.Value = dateTimePicker1.Value.AddDays(-1);
        }

        private void skinButton2_Click(object sender, EventArgs e)
        {
            dateTimePicker1.Value = dateTimePicker1.Value.AddDays(1);
        }

        private void OrderList_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                var r = OrderList.HitTest(e.X, e.Y);
                scr = r.RowIndex;
                scc = r.ColumnIndex;
                waitforup = true;
            }
        }

        private int scr = 0; // 开始点下的格子row
        private int scc = 0; // 开始点下的格子column
        private int ecr = 0; // 结束点下的格子row
        private int ecc = 0; // 结束点下的格子column
        private bool waitforup = false;

        private void OrderList_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (!waitforup)
                {
                    return;
                }

                var r = OrderList.HitTest(e.X, e.Y);
                ecr = r.RowIndex;
                ecc = r.ColumnIndex;

                if (ecr != scr || scc != ecc) // 判断是不是 不同一个格子 说明发生了拖拽
                {
                    if (ecr == -1 && ecc == -1 && OrderList.Rows[scr].Cells[scc].Tag != null) // 往外拖拽 并且格子不为空
                    {
                        DialogResult r2 = MessageBox.Show("确实要删除这一条预约吗？不可撤销", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (r2 == DialogResult.Yes)
                        {
                            string sql2 = "delete from Book where Order_ID=" + OrderList.Rows[scr].Cells[scc].Tag.ToString();
                            DB.Execute(sql2);
                            LoadOrders();
                        }
                    }
                    else if (OrderList.Rows[scr].Cells[scc].Tag != null) // 判断起始的格子是不是空格子 不为空 那说明拖拽源有效
                    {
                        if (OrderList.Rows[ecr].Cells[ecc].Tag != null) // 目标格子必须为空
                        {
                            MessageBox.Show("目标时间已被预约，请选择另一个！", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            // 条件满足，开始转移操作
                            string sourceID = OrderList.Rows[scr].Cells[scc].Tag.ToString();
                            DataView source = DB.GetDs("select * from Book where Order_ID=" + sourceID).Tables[0].DefaultView;


                            // 0 病人姓名
                            // 1 预约时间
                            // 2 源医生姓名
                            // 3 改之后的时间
                            // 4 改之后的医生姓名
                            string msg = string.Format("确实要将{0}病人在{1}预约的{2}医生改到{3}的{4}医生？",
                                                       DB.GetData("select Patient_Name from Patient where Patient_ID=" + source[0]["Patient_ID"].ToString()).ToString(),
                                                       Convert.ToDateTime(DB.GetData("select Order_Time from Book where Order_ID=" + sourceID).ToString()).ToString("yyyy-MM-dd hh:mm"),
                                                       OrderList.Columns[scc].HeaderText,
                                                       dateTimePicker1.Value.ToString("yyyy-MM-dd") + " "  + OrderList.Rows[ecr].Cells[0].Value.ToString(),
                                                       OrderList.Columns[ecc].HeaderText);
                            DialogResult r2 = MessageBox.Show(msg, "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (r2 == DialogResult.Yes)
                            {
                                string sql = string.Format("update Book set User_ID={0},Order_Time='{1}' where Order_ID=" + source[0]["Order_ID"].ToString(),
                                                            OrderList.Columns[ecc].Name,
                                                            dateTimePicker1.Value.ToString("yyyy-MM-dd ") + OrderList.Rows[ecr].Cells[0].Value.ToString());
                                DB.Execute(sql);
                                LoadOrders();
                            }
                        }
                    }
                }
            }
            waitforup = false;
        }
    }
}
